package cn.szabadsag.utils;

import cn.szabadsag.org.mapper.EmployeeMapper;
import cn.szabadsag.user.domain.LoginInfo;
import cn.szabadsag.user.mapper.UserMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 当前登录用户工具类
 *
 * @author yangcong
 * @date 2022年03月15日 15:01
 * @since v1.0
 */
public class LoginContext {

    /**
     * 返回值类型中有前台用户1,也有后台管理员用户0
     * @param request
     * @return
     */
    public static Object getCurrentUser(HttpServletRequest request){
        //  通过请求头获取当前登录用户的信息    此项目前端的请求头设置为U-TOKEN
        String token = request.getHeader("U-TOKEN");
        System.out.println("通过请求头获取当前登录用户的信息:" + token);
        //  获取Spring容器
        WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
        //  从容器里面获取指定的对象
        RedisTemplate redisTemplate = webApplicationContext.getBean("redisTemplate", RedisTemplate.class);
        //  从Redis中获取用户信息
        LoginInfo loginInfo = (LoginInfo) redisTemplate.opsForValue().get(token);
        //  后台用户
        if (loginInfo.getType() == 0){
            EmployeeMapper employeeMapper = webApplicationContext.getBean(EmployeeMapper.class);
            return employeeMapper.loadByLoginInfoId(loginInfo.getId());
        }else {
            //  前台用户
            UserMapper userMapper = webApplicationContext.getBean(UserMapper.class);
            return userMapper.loadByLoginInfoId(loginInfo.getId());
        }
    }

}
